package velox.jcr.mapper.declarative;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Value;

import org.springframework.beans.BeanWrapper;

import velox.jcr.mapper.ValueMapper;

public class CollectionMapping implements Mapping {

	private String javaProperty;
	private String jcrProperty;
	private ValueMapper valueMapper;

	public CollectionMapping(String javaProperty, String jcrProperty, ValueMapper valueHandler) {
		this.javaProperty = javaProperty;
		this.jcrProperty = jcrProperty;
		this.valueMapper = valueHandler;
	}

	public String getJavaProperty() {
		return javaProperty;
	}

	public void read(Node node, BeanWrapper destination) throws RepositoryException {
		List dest = new ArrayList();
		Value[] values = node.getProperty(jcrProperty).getValues();
		for (Value v : values) {
			dest.add(valueMapper.handle(v));
		}
		destination.setPropertyValue(javaProperty, dest);
	}

	public void readFromCache(Map<String, Object> cache, BeanWrapper destination) {
		destination.setPropertyValue(javaProperty, cache.get(jcrProperty));
	}

	public void write(Node node, BeanWrapper object, boolean create) throws RepositoryException {
		List l = (List) object.getPropertyValue(javaProperty);
		if (l == null) {
			node.setProperty(jcrProperty, new String[] {});
		} else {
			String[] dest = new String[l.size()];
			int i = 0;
			for (Object o : l) {
				dest[i++] = valueMapper.convert(o);
			}
			node.setProperty(jcrProperty, dest);
		}
	}

	public void writeToCache(Map<String, Object> cache, BeanWrapper object) {
		cache.put(jcrProperty, object.getPropertyValue(javaProperty));
	}

}
